package com.CMC.yhdeng;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.provider.Settings.System;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.util.JsonReader;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.CMC.yhdeng.ExamUnitContent.ExamType;

public abstract class QuizBaseActivity extends Activity {
	public enum QuizMode{
		QM_Unknow, QM_Practice, QM_Test, QM_History
	}
protected enum MPState{
	MP_Idle, MP_Preparing, MP_Started, MP_Invalid
}
	protected String timeHintFormat;
	protected RelativeLayout rlytInputArea;
	protected TextView txtCorrectQz, txtWrongQz, txtScores;
	protected CountDownTimer cdt;
	protected TextView txtTimeHint;
	protected ImageView ivCorrectAnswer, ivWrongAnswer;
	private Boolean bCorrect;
	protected Button btnYes, btnCancel;
	protected ImageView ivAnsMic;
//	private TextView tvQuestion;
	protected QuizMode quizType;
	protected EditText etAnswer;	
//	protected TextView txtSub;
	MediaPlayer mPlayer;
	MPState sta=MPState.MP_Idle;
    protected QuizDisplay qdView;
	ExamUnitContent examUnit;
	QuizColl quizList;
	QuizContent curQuiz;
    public void playSound(String url) {

		switch (sta) {
			case MP_Started:
				mPlayer.reset();
			case MP_Idle: {
				try {
					mPlayer.setDataSource(url);
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SecurityException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				mPlayer.prepareAsync();
				sta=MPState.MP_Preparing;
			}
			break;
			case MP_Preparing:
				break;
			
				
				
			case MP_Invalid:
				break;

		}

    }
   
	protected void clickYes()
	{
		updateAnswerState();
	}
	
	protected void setQuizVisiblity(int b)
	{
//		tvQuestion.setVisibility(b);
	}
	protected void setQuizContent(QuizContent qc)
	{
		qdView.setContent(qc);
	}
	protected void findViews()
	{
		rlytInputArea=(RelativeLayout )findViewById(R.id.rlytInput);
		txtCorrectQz=(TextView)findViewById(R.id.txtCorrectQuizs);
		txtWrongQz=(TextView)findViewById(R.id.txtWrongQuizs);
		txtScores=(TextView)findViewById(R.id.txtScores);
		txtTimeHint=(TextView)(findViewById(R.id.lytBase).findViewById(R.id.txtTestTime));
		ivAnsMic=(ImageView)findViewById(R.id.ivAnsMIc); 
//		tvQuestion=(TextView)findViewById(R.id.txtChapterTitle);
		qdView=(QuizDisplay)findViewById(R.id.qdChapterTitle);
		btnYes=(Button)findViewById(R.id.btnYes);
		btnYes.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				clickYes();
				
			}
		});
		
		etAnswer=(EditText )findViewById(R.id.edtAnsInput);
		etAnswer.setOnEditorActionListener(new EditText.OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				btnYes.performClick();
				return true;
			}
		});
		btnCancel=(Button)findViewById(R.id.btnCancel);
		btnCancel.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				etAnswer.setText("");
				
			}
		});
		ivCorrectAnswer=(ImageView)findViewById(R.id.ivCorrectAnswer);
		ivWrongAnswer=(ImageView)findViewById(R.id.ivWrongAnswer);

		timeHintFormat="測驗時間：%02d:%02d";
//		txtSub=(TextView)findViewById(R.id.tvSub);
	}
	
	protected abstract void tick();
	protected void timeUp()
	{
		endQuiz();
	}




	@Override
	protected void onStop(){
//		cdt.cancel();
		mPlayer.release();
		mPlayer=null;
		endCountDownTimer();
		super.onStop();
	}
	@Override
	protected void onStart() {
		super.onStart();
		mPlayer = new MediaPlayer();
		mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
			
			@Override
			public void onPrepared(MediaPlayer mp) {
				sta=MPState.MP_Started;
				mp.start();
				
			}
		});
		
		mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
			
			@Override
			public void onCompletion(MediaPlayer mp) {
				mp.reset();
				sta=MPState.MP_Idle;
				
			}
		});
		
		mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
			
			@Override
			public boolean onError(MediaPlayer mp, int what, int extra) {
				// TODO Auto-generated method stub
				return false;
			}
		});
		
		new AsyncTask<String, Void, List>() {

			@Override
			protected List doInBackground(String... params) {
				Resources reso=QuizBaseActivity.this.getResources();
				String sUrlApi=reso.getString(R.string.api_url);
				String sUrlExamContent=reso.getString(R.string.api_get_exam);
				String sUrl=String.format("%s%s/%s", sUrlApi, sUrlExamContent, (String)params[0]); 
				try {
					return downloadUrl(sUrl);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
				return null;
			}

			@Override
			protected void onPostExecute(List result) {
				//downloaded all quizs
				quizList=new QuizColl(result, quizType);
				
				curQuiz= quizList.next();
				
				startCountDownTimer( (2+examUnit.time)*1000, 1000);
				
				TextView tvSub=(TextView )findViewById(R.id.tvSub);
				String s=String.format("總共 %d 題", quizList.getObjs().size());
				tvSub.setText(s);
				updateScenseAfterQuizInfoDownloaded();
				super.onPostExecute(result);
			}
			
		}.execute(examUnit.id);
		
		
	}

	protected void updateScenseAfterQuizInfoDownloaded()
	{
		
	}
	protected void endCountDownTimer()
	{
		if(cdt!=null)
		{
			cdt.cancel();
			cdt=null;
		}
	}
	protected long sSpendingTime;
	protected void startCountDownTimer(long t1, long t2)
	{
		cdt=new CountDownTimer(t1, t2) {

		     public void onTick(long millisUntilFinished) {
		    	 
		    	 Time ti=new Time();
		    	 ti.set(millisUntilFinished);
		    	 
//		    	 long sec=millisUntilFinished/1000;
//		    	 long min=sec/60;
//		    	 sec-=min*60;

		    	 int min=ti.minute;
		    	 int sec=ti.second;
		    	 
		    	 sSpendingTime=millisUntilFinished;
//		    	 String ss=(String) txtTimeHint.getText();
		    	 txtTimeHint.setText(String.format(timeHintFormat, min, sec));
		    	 tick();
		     }

		     public void onFinish() {
		    	 String sRes=String.format(timeHintFormat, 0, 0);
		    	 txtTimeHint.setText(sRes);
		         timeUp();
		     }
		  }.start();
	}
	protected void answerChecked()
	{
		
		curQuiz=quizList.next();
	}
	protected void popupAnswerResultView(Boolean isCorrect)
	{
		etAnswer.setText("");
		bCorrect=isCorrect;
		if(bCorrect) ivCorrectAnswer.setVisibility(View.VISIBLE);
		else ivWrongAnswer.setVisibility(View.VISIBLE);
			
		new CountDownTimer(1500, 1500) {
			
			@Override
			public void onTick(long millisUntilFinished) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onFinish() {
				if(bCorrect)ivCorrectAnswer.setVisibility(View.INVISIBLE);
				else ivWrongAnswer.setVisibility(View.INVISIBLE);
				answerChecked();
			}
		}.start();
	}

	protected void filterQuiz(ExamType type) {
		
		String objName = getResources().getString(
				R.string.quiz_type_serializable);
		examUnit = (ExamUnitContent) getIntent().getExtras().getSerializable(
				objName);
		
		
		quizType= (QuizMode) getIntent().getExtras().get(getResources().getString(R.string.quiz_type_extra_tag));
//		if(quizType==quizty)
	}
	protected List readJsonStream(InputStream in) throws IOException 
	{
//		Log.d("debug",in.toString());
	     JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
//	     try {
	    	 //read book array
	 		reader.beginArray();
	 		ArrayList<QuizContent> lst=new ArrayList<QuizContent>();
	 		String sep=getResources().getString(R.string.quiz_content_seperate_tag);
	 		while (reader.hasNext()) {// read a book
	 			
	 			QuizContent qc=new QuizContent();
	 			qc.read(reader, sep);
	 			Log.d("readJsonStream", qc.title);
	 			if(qc.title.compareTo("record")==0)
	 			{
	 				Log.d("readJsonStream","!!");
	 			}
//	 			if( (qc.is_practice && quizType==QuizMode.QM_Practice) ||  
	 			lst.add(qc);
	 			
	 		}
			reader.endArray();
			
			reader.close();
			return lst;

	   }
	public String convertStreamToString(InputStream is) throws IOException {
		//
		// To convert the InputStream to String we use the
		// Reader.read(char[] buffer) method. We iterate until the
		// Reader return -1 which means there's no more data to
		// read. We use the StringWriter class to produce the string.
		//
		if (is != null) {
			Writer writer = new StringWriter();

			char[] buffer = new char[1024];
			try {
				Reader reader = new BufferedReader(new InputStreamReader(is,
						"UTF-8"));
				int n;
				while ((n = reader.read(buffer)) != -1) {
					writer.write(buffer, 0, n);
				}
			} finally {
				is.close();
			}
			return writer.toString();
		} else {
			return "";
		}
	}
	
	protected List downloadUrl(String myurl) throws IOException {
		InputStream is = null;
		try {
			URL url = new URL(myurl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(15000 /* milliseconds */);
			conn.setConnectTimeout(20000 /* milliseconds */);
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			// Starts the query
			conn.connect();
			int response = conn.getResponseCode();
			Log.d("debug", "The response is: " + response);
			is = conn.getInputStream();

//			String ss=convertStreamToString(is);
//			Log.d("ss", ss);
			return readJsonStream(is);
			

		} finally {
			// Makes sure that the InputStream is closed after the app is
			// finished using it.
			if (is != null) {
				is.close();
			}
		}
	}
	
	private void uploadScoreInfo(final List<NameValuePair> nameValuePairs)
	{
		new AsyncTask<String, Void, String>(){

			@Override
			protected String doInBackground(String... params) {
				String stringUrl = "http://www.urjotter.com/apis/exam/postScore";
				try {
					HttpClient httpclient = new DefaultHttpClient();		
				    HttpPost httppost = new HttpPost(stringUrl);

				    
				        // Add your data
//				        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
				        
//				        nameValuePairs.add(new BasicNameValuePair("userid", "JoshTest"));
//				        nameValuePairs.add(new BasicNameValuePair("exam_id", "60"));
//				        nameValuePairs.add(new BasicNameValuePair("exam_time", "71"));
//				        nameValuePairs.add(new BasicNameValuePair("finish_datetime", "2014-05-03 16:14:56"));
//				        nameValuePairs.add(new BasicNameValuePair("is_exam", "1"));
//				        nameValuePairs.add(new BasicNameValuePair("is_pass", "1"));
//				        nameValuePairs.add(new BasicNameValuePair("score", "82"));
				        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

				        // Execute HTTP Post Request
				        HttpResponse response = httpclient.execute(httppost);
				} catch (IOException e) {
					Log.d("test", e.getMessage());
					e.printStackTrace();
				}
				return null;
			}

			@Override
			protected void onPostExecute(String result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
			}
			
		}.execute("abc");

	}
	public Dialog onCreateDialog(Bundle savedInstanceState) {
	    AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    // Get the layout inflater
	    LayoutInflater inflater = getLayoutInflater();

	    // Inflate and set the layout for the dialog
	    // Pass null as the parent view because its going in the dialog layout
	    LinearLayout ll=(LinearLayout)inflater.inflate(R.layout.alert_dlg, null);
	    //set layout content
	    TextView tvCorrect=(TextView)ll.findViewById(R.id.tvCorrectNum);
	    TextView tvIncorrect=(TextView)ll.findViewById(R.id.tvIncorrectNum);
	    TextView tvTime=(TextView)ll.findViewById(R.id.tvTime);
	    
	    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(12);
        nameValuePairs.add(new BasicNameValuePair("userid", "Anonymous"));
        
        nameValuePairs.add(new BasicNameValuePair("exam_id", examUnit.id));
        long realSpendingTime=examUnit.time*1000-sSpendingTime;
        Long secSpending=realSpendingTime/1000;
        nameValuePairs.add(new BasicNameValuePair("exam_time", secSpending.toString()));
        java.util.Date date =Calendar.getInstance().getTime();
        java.text.DateFormat df=java.text.DateFormat.getDateTimeInstance();
        
        String format="yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.TRADITIONAL_CHINESE);
		
        String s_finish_datetime=sdf.format(date);
        nameValuePairs.add(new BasicNameValuePair("finish_datetime", s_finish_datetime));
        nameValuePairs.add(new BasicNameValuePair("is_exam", quizType==QuizMode.QM_Test ? "1" : "0"));
        nameValuePairs.add(new BasicNameValuePair("is_pass", "0"));
        
	    float iCorr=quizList.getCorrectPoints();
	    int percent=(int)(iCorr/quizList.getObjs().size()*100.0);
	    String sCorr= String.format("答對的題數 %d，答對的比例 %d%%", (int)iCorr, percent);
	    tvCorrect.setText(sCorr);
	    Integer score=percent;
	    nameValuePairs.add(new BasicNameValuePair("score", score.toString()));
	    
	    sCorr=String.format("答錯的題數 %d，答錯的比例 %d%%", (int)(quizList.getObjs().size()-iCorr), 100-percent);
	    tvIncorrect.setText(sCorr);
	    
	    Time ti=new Time();
	    ti.set(realSpendingTime);
	    
	    sCorr=String.format("時間 %d:%d", ti.minute, ti.second);
	    tvTime.setText(sCorr);
	    
	    uploadScoreInfo(nameValuePairs);
	    
	    builder.setView(ll)
	    // Add action buttons
	           .setPositiveButton(R.string.qba_alert_ok, new DialogInterface.OnClickListener() {
	               @Override
	               public void onClick(DialogInterface dialog, int id) {
	                   // sign in the user ...
	               }
//	           })
//	           .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
//	               public void onClick(DialogInterface dialog, int id) {
////	                   LoginDialogFragment.this.getDialog().cancel();
//	               }
	           });      
	    return builder.create();
	}
	protected void endQuiz()
	{
		endCountDownTimer();
		mPlayer.reset();
		showQuizResult();
	}
	
	protected void showQuizResult()
	{
		onCreateDialog(null).show();
	}
	protected void updateAnswerState()
	{
		int n=quizList.getObjs().size();
		int correctNum=quizList.getCorrectPoints();
		int score=(int) ((float)correctNum/n*100.0);
		
		txtScores.setText(Integer.toString(score));
		txtWrongQz.setText(String.format("%d", quizList.getWrongPoints()));
		txtCorrectQz.setText(String.format("%d", correctNum));
	}
	 void showToastMessage(String message){
		  Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
		 }
	 

}
